package com.renyi.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.renyi.http.HttpResult;
import com.renyi.http.ParamBean;
import com.renyi.model.MybatisService;
import com.renyi.pay.zfb.AlipayNotify;
import com.renyi.pay.zfb.CallBackZFBInfo;
import com.renyi.util.JSONUtils;
import com.renyi.util.OrderUtil;

/**
 * 
 * @author shs
 * 
 */
@Controller
public class PayController extends BaseController {

	@Autowired
	private MybatisService mybatisService;

	// 支付宝-回调
	@RequestMapping("/payZFB")
	public void payZFB(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 返回结果
		HttpResult result = new HttpResult();
		try {
			// 获取支付宝POST过来反馈信息
			Map<String, Object> params = new HashMap<String, Object>();
			Map requestParams = request.getParameterMap();
			for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
				}
				// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
				// valueStr = new String(valueStr.getBytes("ISO-8859-1"),
				// "gbk");
				params.put(name, valueStr);
			}
			// 按类对象获取
			CallBackZFBInfo cZFB = super.getJsonParamPay(request, CallBackZFBInfo.class);

			// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
			// 商户订单号
			String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

			// 支付宝交易号
			String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

			// 交易状态
			String trade_status = cZFB.getTrade_status();
			int uKey = -1;
			if (AlipayNotify.verify(params)) {// 验证成功
				//////////////////////////////////////////////////////////////////////////////////////////
				// 请在这里加上商户的业务逻辑程序代码

				// ——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

				if (trade_status.equals("TRADE_FINISHED")) {
					// 判断该笔订单是否在商户网站中已经做过处理
					// 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					// 如果有做过处理，不执行商户的业务程序

					// 注意：
					// 退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
					// 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
				} else if (trade_status.equals("TRADE_SUCCESS")) {
					// 判断该笔订单是否在商户网站中已经做过处理
					// 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					// 如果有做过处理，不执行商户的业务程序
					int iKey = (Integer) this.mybatisService.insertIbatisObject("payZFBSQL", params);
					// Z-咨询 Y-药品 C-个人账户充值 K-个人账户扣款
					if (!TextUtils.isEmpty(out_trade_no)) {
						String type = out_trade_no.substring(0, 1);
						if (type.equals("Z")) {
							uKey = (Integer) this.mybatisService.insertIbatisObject("updateRecordZFBSQL", params);
							if(uKey>0){
								List<HashMap<String, Object>> data = this.mybatisService.findMybatisList("getZRecordSQL", params);
								if(data.size()>0){
									String pTel =data.get(0).get("PatientQQ").toString();
									String dTel = data.get(0).get("DoctorQQ").toString();
									if(!"".equals(pTel)&&!"".equals(dTel)){
										pTel = pTel.substring(0,pTel.length()-1);
										dTel = dTel.substring(0,dTel.length()-1);
										this.sendPaySMS(dTel, "亲，手机号"+pTel+"的用户向您发起在线咨询，请及时关注", "短信通知");
									}
											
								}
							}
						} else if (type.equals("Y")) {
							uKey = (Integer) this.mybatisService.insertIbatisObject("updateMedicineOrderZFBSQL",
									params);
						} else if (type.equals("B")) {// 门诊订单付款
							uKey = (Integer) this.mybatisService.insertIbatisObject("updateMSOrderZFBSQL", params);
							if (uKey > 0) {
								uKey = (Integer) this.mybatisService.insertIbatisObject("updateMSOrderTwoZFBSQL",
										params);
							}

						} else if (type.equals("K")) {// 康美

							List<HashMap<String, Object>> listRes = this.mybatisService
									.procedureMybatisList("KMMedicineOrderZFBSQL", params);
							String resType = "";
							if (listRes.size() > 0) {
								resType = listRes.get(0).get("resType") != null
										? listRes.get(0).get("resType").toString() : "0";
								if (resType.equals("0")) {
									uKey = 1;
								} else {
									uKey = 0;
								}

							}
							uKey = (Integer) this.mybatisService.insertIbatisObject("updateMedicineOrderZFBSQL",
									params);
						} else if (type.equals("M")) {
							String uid = out_trade_no.substring(1, out_trade_no.indexOf(",") - 1);
							String orderIDList = out_trade_no.substring(out_trade_no.indexOf(",") + 1);
							params.put("uid", uid);
							params.put("orderIDList", orderIDList);
							params.put("orderID", OrderUtil.getOrderID("Y"));
							List<HashMap<String, Object>> listRes = this.mybatisService
									.procedureMybatisList("mergeMedicineOrderZFBSQL", params);
							String resType = "";
							if (listRes.size() > 0) {
								resType = listRes.get(0).get("resType") != null
										? listRes.get(0).get("resType").toString() : "0";
								if (resType.equals("0")) {
									uKey = 1;
								} else {
									uKey = 0;
								}

							}
						} else if (type.equals("C")) {
							uKey = (Integer) this.mybatisService.insertIbatisObject("updateAccountZFBSQL", params);
							// }
							// else if (type.equals("K")) {
							// uKey = (Integer)
							// this.mybatisService.insertIbatisObject("updateAccountKKZFBSQL",
							// params);
						} else if (type.equals("T")) {// 收费
							List<HashMap<String, Object>> resultList = this.mybatisService
									.findMybatisList("updateBlxxBlzt", params);
							if (resultList != null && resultList.size() > 0) {
								HashMap<String, Object> resultMap = resultList.get(0);
								uKey = (Integer) resultMap.get("result");
							}
						}
					}

					// 注意：
					// 付款完成后，支付宝系统发送该交易状态通知
					// 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
				}
				if (uKey > 0) {
					this.ajaxResultJson(response, "success");
				}

			} else {
				this.ajaxResultJson(response, "fail");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(-1);
			result.setMsg(e.getMessage());
			;// //错误消息
			this.ajaxResultJson(response, result);
		}
	}

	
}
